package com.wx.tnsperson.controller;


import com.alibaba.fastjson.JSONException;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.wx.common.api.CommonResult;
import com.wx.common.api.ResultCode;
import com.wx.tnsperson.service.MyRedisService;
import com.wx.tnsperson.service.ProRegisterAndLoginService;
import com.wx.tnsperson.vo.ResumeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.Random;


/**
 * @Author:LLH
 * @Date:2020/7/24
 */
@CrossOrigin
@RequestMapping(value = "/user")
@RestController
@Api(tags = "个人注册&&登录")
public class ProRegisterAndLoginController {


    @Autowired
    private HttpSession session;
    @Autowired
    private ProRegisterAndLoginService proRegisterAndLoginService;
    @Autowired
    MyRedisService redisService;

    //设置验证码过期时间为1分钟
    private static long CODE_EXPIRE_SECONDS = 60;

    //正则验证手机号是否合法
    private static String PATTEN_REGEX_PHONE = "^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$";

    @ApiOperation(value = "用户手机号密码注册", notes = "用户手机号密码注册")
    @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
    public CommonResult registerUser ( @RequestBody(required = false) ResumeVo resumeVo ) {
        boolean rVo = proRegisterAndLoginService.loginPhone ( resumeVo.getPhone ( ) );
        try {
            if (resumeVo.getPhone ( ) == "" || resumeVo.getPhone ( ) == null || resumeVo.getPhone ( ).isEmpty ( )) {
                return CommonResult.failed ( "手机号不能为空!" );
            } else if (!resumeVo.getPhone ( ).matches ( PATTEN_REGEX_PHONE )) {
                return CommonResult.failed ( "手机号不正确,请输入正确的手机号!" );
            } else if (resumeVo.getPassword ( ) == "" || resumeVo.getPassword ( ) == null || resumeVo.getPassword ( ).isEmpty ( )) {
                return CommonResult.failed ( "密码不能为空!" );
            } else if (rVo) {
                proRegisterAndLoginService.registerUser ( resumeVo );
                return CommonResult.success ( resumeVo.getId ( ),"注册成功,该手机号没有被注册。" );
            } else {
                return CommonResult.failed ( "注册失败，该用户手机号已被注册!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    //发送短信
    private String SMS ( String phone ) {
        //手机
        String phoneNumber = phone;
        //短信的内容
        int templateId = 200461;
        //参数
        String[] params = new String[1];
        //验证码
        String code = "";
        Random r = new Random ( );
        for (int i = 0; i < 6; i++) {
            code += r.nextInt ( 10 );
        }
        //将Code放入Session中
        session.setAttribute ( "sms",code );
        params[0] = code;
        System.out.println ( code );
        //签名
        String sign = "领航招聘测试";

        //拿到发送短信的核心类
        SmsSingleSender ssender = new SmsSingleSender ( 1400142856,"21306d751cfdf61ed433e506da242522" );
        //发送短信
        try {
            SmsSingleSenderResult result = ssender.sendWithParam ( "86",phoneNumber,templateId,params,sign,"","" );
            System.out.println ( result );
        } catch (JSONException | HTTPException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace ( );
        } catch (com.github.qcloudsms.httpclient.HTTPException e) {
            e.printStackTrace ( );
        }
        return code;
    }

    @ApiOperation(value = "获取注册验证码", notes = "获取注册验证码")
    @RequestMapping(value = "/getRegisterCode", method = RequestMethod.GET)
    public CommonResult smsRegisterCode ( String phone ) {
        System.out.println ( phone );
        //保护机制，如果用户已经注册过了，我们就不用给他发短信了
        //通过phone查找用户，看其是否注册过，如果注册过了，我们就不用给他发短信
        //如果没有注册，我们才需要给他发短信
        //表示该用户存不存在  select * from pro_userInfo where phone = ?
        boolean rVo = proRegisterAndLoginService.loginPhone ( phone );
        //校验手机号
        if (!phone.matches ( PATTEN_REGEX_PHONE )) {
            return CommonResult.failed ( "请输入正确的手机号!" );
            //该用户没有注册
        } else if (rVo) {
            //发送短信
            String sms = SMS ( phone );
            //清除未失效的key对应的value值
            redisService.remove ( phone );
            //缓存新的key-value值
            redisService.set ( phone,sms );
            //设置过期时间   CODE_EXPIRE_SECONDS
            redisService.expire ( phone,CODE_EXPIRE_SECONDS );
            System.out.println ( "注册验证码已发送，请注意查收,该用户手机号没有被注册!" );
            return CommonResult.success ( sms,"注册验证码已发送，请注意查收,该用户手机号没有被注册!" );
        }
        //用户已经注册过了
        else {
            System.out.println ( "该用户手机号已经注册！" );
            return CommonResult.failed ( "该用户手机号已经注册！" );
        }
    }

    @ApiOperation(value = "用户手机号验证码注册", notes = "用户手机号验证码注册")
    @RequestMapping(value = "/registerCode", method = RequestMethod.POST)
    public CommonResult registerPhone ( @RequestBody(required = false) ResumeVo resumeVo ) {
        String code = redisService.get ( resumeVo.getPhone ( ) );
        String authCode = resumeVo.getAuthCode ( );
        boolean rVo = proRegisterAndLoginService.loginPhone ( resumeVo.getPhone ( ) );
        try {
            if (resumeVo.getPhone ( ) == "" || resumeVo.getPhone ( ) == null || resumeVo.getPhone ( ).isEmpty ( )) {
                return CommonResult.failed ( "手机号不能为空!" );
            } else if (!resumeVo.getPhone ( ).matches ( PATTEN_REGEX_PHONE )) {
                return CommonResult.failed ( "手机号不正确,请输入正确的手机号!" );
            } else if (StringUtils.isEmpty ( code )) {
                return CommonResult.failed ( "注册验证码已经失效,请重新获取验证码!" );
            } else if (!authCode.equals ( code ) && !"".equals ( code )) {
                return CommonResult.failed ( "注册验证码错误,请输入正确的验证码!" );
            } else if (rVo) {
                proRegisterAndLoginService.registerPhone ( resumeVo );
                System.out.println ( "注册成功,该手机号没有被注册。" );
                return CommonResult.success ( resumeVo.getId ( ),"注册成功,该手机号没有被注册。" );
            } else {
                return CommonResult.failed ( "注册失败,该用户手机号已被注册!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }

    }


    @ApiOperation(value = "用户手机号密码登录", notes = "用户手机号密码登录")
    @RequestMapping(value = "/loginUser", method = RequestMethod.POST)
    public CommonResult loginUser ( @RequestBody(required = false) ResumeVo resumeVo ) {
        // select * from   pro_userInfo where  phone=? and password=?
        ResumeVo rVo = proRegisterAndLoginService.loginUser ( resumeVo );
        try {
            if (resumeVo.getPhone ( ) == "" || resumeVo.getPhone ( ) == null || resumeVo.getPhone ( ).isEmpty ( )) {
                return CommonResult.failed ( "手机号为空,登录失败!" );
            } else if (resumeVo.getPassword ( ) == "" || resumeVo.getPassword ( ) == null || resumeVo.getPassword ( ).isEmpty ( )) {
                return CommonResult.failed ( "密码为空,登录失败!" );
            } else if (null == rVo) {
                return CommonResult.failed ( "手机号或密码错误,登录失败!" );
            } else {
                return CommonResult.success ( rVo,"手机号、密码正确,登录成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }


    @ApiOperation(value = "获取登录验证码", notes = "获取登录验证码")
    @RequestMapping(value = "/getLoginCode", method = RequestMethod.GET)
    public CommonResult smsLoginCode ( String phone ) {
        System.out.println ( phone );
        //用户存在  select * from pro_userInfo where phone = ?
        boolean rVo = proRegisterAndLoginService.loginPhone ( phone );
        if (!rVo) {
            //发送短信
            String sms = SMS ( phone );
            redisService.remove ( phone );
            //缓存新的key-value值
            redisService.set ( phone,sms );
            //设置过期时间   CODE_EXPIRE_SECONDS
            redisService.expire ( phone,CODE_EXPIRE_SECONDS );
            System.out.println ( "登录验证码已发送，请注意查收，用户已经注册,请及时登录！" );
            return CommonResult.success ( sms,"登录验证码已发送，请注意查收，用户已经注册,请及时登录！！" );
        }
        //用户不存在
        else {
            System.out.println ( "用户手机号不存在！" );
            return CommonResult.failed ( "用户手机号不存在！" );
        }
    }

    @ApiOperation(value = "用户手机号验证码登录", notes = "用户手机号验证码登录")
    @RequestMapping(value = "/loginCode", method = RequestMethod.POST)
    public CommonResult loginPhone ( @RequestBody(required = false) ResumeVo resumeVo ) {
        String code1 = redisService.get ( resumeVo.getPhone ( ) );
        String authCode = resumeVo.getAuthCode ( );
        ResumeVo rVo = proRegisterAndLoginService.findByPhone ( resumeVo );
        try {
            if (null == rVo) {
                return CommonResult.failed ( "手机号错误,登录失败!" );
            } else if (StringUtils.isEmpty ( code1 )) {
                return CommonResult.failed ( "登录验证码已经失效,请重新获取验证码!" );
            } else if (!authCode.equals ( code1 ) && !"".equals ( code1 )) {
                return CommonResult.failed ( "登录验证码错误,请输入正确的验证码!" );
            } else {
                System.out.println (rVo );
                return CommonResult.success ( rVo,"登录成功" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }




    @ApiOperation(value = "手机号获取ID", notes = "手机号获取ID")
    @RequestMapping(value = "/findByPhone", method = RequestMethod.GET)
    public CommonResult findByPhone (  ResumeVo resumeVo ) {
        ResumeVo byPhone = proRegisterAndLoginService.findByPhone ( resumeVo );
        try {
            if(byPhone==null){
                return CommonResult.failed ( "手机号获取ID查询失败!" );
            }else {
                System.out.println (byPhone.getId () );
                return CommonResult.success ( byPhone.getId (),"手机号获取ID查询成功" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

}
